//
//  ST_RecommendPecVideoCell.swift
//  btvideo
//
//  Created by mac on 2020/6/8.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SnapKit


class ST_RecommendPecVideoCell: UICollectionViewCell {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.contentView.backgroundColor = .black
        
        contentView.addSubview(cover_image_view)
        cover_image_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        contentView.addSubview(playerView)
        playerView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }

        //        弹幕
        self.contentView.addSubview(barrage_container_view)
        barrage_container_view.snp.makeConstraints { (make) in
            make.height.equalTo(ST_TenLineBarrageView.height)
            make.left.right.equalTo(self)
            make.top.equalTo(self).offset(97-20+statusBarHeight)
        }
        
        
        contentView.addSubview(comment_btn)
        comment_btn.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-17)
            make.bottom.equalToSuperview().offset(-164-BTSafeAreaBottom)
            make.width.equalTo(36)
            make.height.equalTo(36+18+3)
        }
        
        
        contentView.addSubview(love_btn)
        love_btn.snp.makeConstraints { (make) in
            make.width.height.right.equalTo(comment_btn)
            make.bottom.equalTo(comment_btn.snp.top).offset(-25)
        }
        
        contentView.addSubview(avatar_image_view)
        avatar_image_view.snp.makeConstraints { (make) in
            make.width.height.equalTo(50)
            make.right.equalToSuperview().offset(-10)
            make.bottom.equalTo(love_btn.snp.top).offset(-35)
        }
        
        contentView.addSubview(follow_btn)
        follow_btn.snp.makeConstraints { (make) in
            make.width.height.equalTo(20)
            make.centerX.equalTo(avatar_image_view)
            make.centerY.equalTo(avatar_image_view.snp.bottom)
        }
        
        contentView.addSubview(gradient_view)
        gradient_view.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(200+BTSafeAreaBottom)
        }
        
        contentView.addSubview(bottom_input_view)
        bottom_input_view.snp.makeConstraints { (make) in
            make.right.left.equalToSuperview()
            make.bottom.equalToSuperview().offset(-17)
            make.height.equalTo(ST_RecommendVIdeoBottomView.height)
        }
        
        contentView.addSubview(video_progress_view)
        video_progress_view.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            if iPhoneXSeries{
                make.bottom.equalToSuperview().offset(-BTSafeAreaBottom)
            }else{
                make.top.equalToSuperview().offset(20)
            }
            make.height.equalTo(ST_PlayVideoProgressView.height)
        }
        
        contentView.addSubview(content_label)
        content_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.bottom.equalToSuperview().offset(-72-BTSafeAreaBottom)
            make.right.equalToSuperview().offset(-15)
        }
        
        contentView.addSubview(nickname_label)
        nickname_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.bottom.equalTo(content_label.snp.top).offset(-10)
            make.height.equalTo(25)
        }
        
        contentView.addSubview(tag_btn)
        tag_btn.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.bottom.equalTo(nickname_label.snp.top).offset(-10)
            make.height.equalTo(ST_BTTagButton.height)
        }
        
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func package(playView:UIView) {
        
        contentView.insertSubview(playView, aboveSubview: cover_image_view)
        
        playView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
    
    
//    MARK: - Properties
    fileprivate lazy var cover_image_view:UIImageView = {
        let control = UIImageView()
        control.backgroundColor = .black
        control.contentMode = UIView.ContentMode.scaleAspectFit
        control.clipsToBounds = true
        return control
    }()
    
    fileprivate lazy var playerView:ST_PeculiarityVideoPlayView = {
        let control = ST_PeculiarityVideoPlayView()
//        control.isUserInteractionEnabled = false
        control.backgroundColor = Color.clear
        control.clipsToBounds = true
        
        control.playDidFinishClosure = {[weak self] in
            self?.play_loop()
        }
        control.playSecondsClosure = {[weak self] s in
            
            guard let duration = self?.child_model?.duration.cgFloat else{
                return
            }

            let d = duration < 1 ? 1 : duration
            
            self?.video_progress_view.setProgress(percentValue: s/d, currentIdx: 0)
        }
        
        
        
        return control
    }()
    
    
    fileprivate lazy var avatar_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = UIView.ContentMode.scaleAspectFill
        control.borderWidth = 1
        control.borderColor = UIColor.white
        control.cornerRadius = 50/2.0
        
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(user_center_click_handle))
        control.isUserInteractionEnabled = true
        control.addGestureRecognizer(tap)
        return control
    }()
    
    fileprivate lazy var follow_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImage(ST_ImageUtils.imageName("特质_video_关注_icon_sel"), for: UIControl.State.selected)
        control.setImage(ST_ImageUtils.imageName("特质_video_关注_icon"), for: UIControl.State.normal)
        control.addTarget(self, action: #selector(follow_click_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
//
    
    fileprivate lazy var love_btn:ST_VerticalButton = {
            
        let control = ST_VerticalButton()
        control.image_view_edges = UIEdgeInsets.init(top: 0, left: 0, bottom: 18+3, right: 0)
        control.title_bottom_offset = 0
        control.setImage(ST_ImageUtils.imageName("视频_love_icon")!, for: UIControl.State.normal)
        control.setImage(ST_ImageUtils.imageName("视频_love_icon_selected")!, for: UIControl.State.selected)
        control.addTarget(self, action: #selector(love_handle), for: .touchUpInside)
        return control
    }()
    
    
    
    lazy var comment_btn_attr: [NSAttributedString.Key : Any] = {
        
        
        let shadow = NSShadow()
        
        shadow.shadowColor = UIColor(red: 0, green: 0, blue: 0,alpha:0.3)
        
        shadow.shadowBlurRadius = 2
        
        shadow.shadowOffset = CGSize(width: 0, height: 0)
        
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 13, weight: UIFont.Weight.medium),.foregroundColor: UIColor(red: 1, green: 1, blue: 1, alpha: 1), .shadow: shadow]
        
        return attr
    }()
    
    fileprivate lazy var comment_btn:ST_VerticalButton = {
            
        let control = ST_VerticalButton()
        control.image_view_edges = UIEdgeInsets.init(top: 0, left: 0, bottom: 18+3, right: 0)
        control.title_bottom_offset = 0
        control.setImageForAllStates(ST_ImageUtils.imageName("视频_评论_icon")!)
        control.addTarget(self, action: #selector(input_comment_handle), for: .touchUpInside)
        return control
    }()
    
    
    fileprivate lazy var gradient_view:ST_FWGradientView = {
            
        let control = ST_FWGradientView()
        control.bgLayer.colors = [UIColor.init(hex: 0xEEEEEE, transparency: 0)!.cgColor,UIColor.init(hex: 0x1D1E20, transparency: 0.5)!.cgColor]
        control.bgLayer.startPoint = CGPoint(x: 0, y: 0)
        control.bgLayer.endPoint = CGPoint(x: 0, y: 1)
        return control
    }()
    
    var beginInput:((Int,String)->())?
    
    fileprivate lazy var bottom_input_view:ST_RecommendVIdeoBottomView = {
            
        let control = ST_RecommendVIdeoBottomView()
        control.beginInput = {[weak self] in
            self?.beginInput?(self?.child_model?.commentType ?? 2,self?.child_model?.group_id.string ?? "")
        }
        return control
    }()
    
    
    fileprivate lazy var video_progress_view:ST_PlayVideoProgressView = {
        let control = ST_PlayVideoProgressView()
        control.create_items(count: 1)
        return control
    }()
    
    
    
    
    fileprivate lazy var content_attr:[NSAttributedString.Key : Any] = {
        let paragraph = NSMutableParagraphStyle()
        paragraph.lineSpacing = 3
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 1, green: 1, blue: 1, alpha: 1),.paragraphStyle:paragraph]
        return attr
    }()
    
    fileprivate lazy var content_label:UILabel = {
        let control = UILabel()
        control.numberOfLines = 0
        
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(push_group_handle))
        control.isUserInteractionEnabled = true
        control.addGestureRecognizer(tap)
        
        return control
    }()
    
    fileprivate lazy var nickname_label:UILabel = {
        let control = UILabel()
        control.textColor = UIColor.white
        control.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.semibold)
        
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(push_group_handle))
        control.isUserInteractionEnabled = true
        control.addGestureRecognizer(tap)
        return control
    }()
    
    
    fileprivate lazy var tag_btn:ST_BTTagButton = {
        let control = ST_BTTagButton()
        control.addTarget(self, action: #selector(push_pec_list_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var barrage_container_view:ST_TenLineBarrageView = {
        let control = ST_TenLineBarrageView()
        control.isUserInteractionEnabled = false
        return control
    }()
    
    
//    MARK: - Bind Model
    weak var child_model:ST_ShowTraitCellModel?
    {
        didSet{
            
            guard let m = child_model else { return  }
            
            refresh_other_data()
            
            
            avatar_image_view.pin_setImage(from: m.avatar.compress_small_image(width: 50*3).url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
            
            cover_image_view.pin_setImage(from: m.imageUrl.compress_image().url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
            
            tag_btn.bind(text: m.featureName)
            
            playerView.alpha = 0
            
            self.barrage_container_view.alpha = 0
            
            self.video_progress_view.setProgress(percentValue: 0, currentIdx: 0)
        }
    }
    
    
    func refresh_other_data()  {
        
        guard let m = child_model else { return  }
        
        let attr = NSMutableAttributedString.init(string: m.sign)
        
        attr.addAttributes(content_attr, range: NSRange.init(location: 0, length: attr.length))
        
        content_label.attributedText = attr
        
        nickname_label.text = "@" + m.nickname
        
        let commentNumber = NSMutableAttributedString.init(string: m.commentCount.st_number_description())
        
        commentNumber.addAttributes(comment_btn_attr, range: NSRange.init(location: 0, length: commentNumber.length))
        
        comment_btn.setTitleForAllStates(commentNumber)
        
        let thumbUpNumber = NSMutableAttributedString.init(string: m.thumbUpCount.st_number_description())
        
        thumbUpNumber.addAttributes(comment_btn_attr, range: NSRange.init(location: 0, length: thumbUpNumber.length))
        
        love_btn.setTitleForAllStates(thumbUpNumber)
        
        love_btn.isSelected = m.isThumbUp
        
        follow_btn.isSelected = m.isAttention
        
    }
    
}

//MARK: - Event
extension ST_RecommendPecVideoCell{
    
    /*
    @objc func play_view_handle(){
        if playState == 0 {
            self.pause_video()
        }else{
            self.play()
        }
    }*/
    
    @objc fileprivate func love_handle(){
        
        
        if BTVerticalAlertViewController.toastBindPhoneRequireAlert(fromController: self.parentViewController) {
            return
        }
        
        guard let model = self.child_model else { return  }
        
        
        self.playerView.isUserInteractionEnabled = false
        
        Thumbup(targetAccid: model.accid, groupId: model.group_id.string, peculiarity_id: model.feature_id.string, thumbUpAction: !model.isThumbUp, fromVC: self.parentViewController) { (err) in
            
            self.love_btn.isSelected = !self.love_btn.isSelected
            self.child_model?.isThumbUp = !model.isThumbUp
            
            let offSet = model.isThumbUp ? 1 : -1
            
            self.child_model?.thumbUpCount += offSet
            
            self.love_btn.isUserInteractionEnabled = err
            
            self.playerView.isUserInteractionEnabled = err
            
            let thumbUpNumber = NSMutableAttributedString.init(string: (self.child_model?.thumbUpCount ?? 0).st_number_description())
            
            thumbUpNumber.addAttributes(self.comment_btn_attr, range: NSRange.init(location: 0, length: thumbUpNumber.length))
            
            self.love_btn.setTitleForAllStates(thumbUpNumber)
            
        } completion: {
        
            self.love_btn.isUserInteractionEnabled = true
            
            print("点赞成功新Api Service")
            
        }
        
    }
    
    @objc fileprivate func follow_click_handle(){
        
        guard let model = self.child_model else{return}
        
        let info = ST_MatchUserInfo.init(accid: model.accid, avatar: model.avatar, nickname: model.nickname)
       
        self.follow_btn.isUserInteractionEnabled = false
        
        PairsLikeAction(info: info, likeAction: true, isReceive: false, fromVC: self.parentViewController,propId:nil) { (code, err , matched) in
            
            self.follow_btn.isUserInteractionEnabled = true
            
            matched?()
            
            if let e = err{
                
                self.parentViewController?.toast(text: e)
                
            }else{
                
                self.follow_btn.isSelected = !self.follow_btn.isSelected
                
                self.child_model?.isAttention = self.follow_btn.isSelected
            }
        
        }
        
    }
    
    
    @objc fileprivate func user_center_click_handle(){
        
        guard let accid = self.child_model?.accid else { return }
        
        let vc = ST_PairsCenterViewController()
        
        vc.accid = accid
        
        let nav = PairsCenterInteractiveNavigationController.init(rootViewController: vc)
        
        nav.overCurrentContext = true
        
        GlobalPresent(toController: nav)
        
    }
    
    @objc fileprivate func input_comment_handle(){
        
        
        
        guard let model = child_model else { return }
         
        let vc = ST_DarkST_CommentListViewController()
        
        vc.groupId = model.group_id
        
        vc.userId = model.accid
        
        vc.featureName = model.featureName
        
        vc.peculiarity_id = model.feature_id.string
        
        vc.type = model.commentType
        
        vc.overCurrentContext  = true
        
        vc.over_current_context_alpha = "0"
        
        GlobalPresent(toController: vc)
        
        vc.send_barrage_closure = {[weak self] str,groupId in
            
            
            if let pVC = self?.parentViewController as? ST_RecommendPecVideoController{
                
                pVC.insertLocalDanmaku(comment:str,groupId:groupId)
            }
        }
        

        
    }
    
    fileprivate func play_loop(){
        
        print("重新播放URL:",self.child_model?.group_id ?? "")
//        playState = 0
        self.playerView.replay()
    }
    
    func play(){
        
        stopVideo()
        
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
        }catch{
            print("AVAudioSession.Category.playback Error")
        }
        
        print("开始播放URL:",self.child_model?.group_id ?? "")
        
        guard let m = child_model , let url = m.videoUrl.url else{
            return
        }
        playerView.alpha = 1
        
//        if m.width > m.height{
            playerView.play(url: url, gravity: AVLayerVideoGravity.resizeAspect)
//        }else{
//            playerView.play(url: url)
//        }
        
        self.display_barrage()
    }
    
    func stopVideo(){
        
        print("暂停播放URL:",self.child_model?.group_id ?? "")
        playerView.stop()
        playerView.alpha = 0
        
        self.barrage_container_view.out_side_stop()
        self.barrage_container_view.alpha = 0
    }
    
    func continuePlay(){
        
        playerView.continuePlay()
    }
    
    func pause_video(){
        
        playerView.pause()
    }
    
    fileprivate func display_barrage(){
        
        guard let id = child_model?.group_id.string else { return }
        
        ST_BTVideoBarrageAdapter.shared.fetch_barrages(groupId: id) {[weak self] (array,num) in
            
            guard let strongSelf = self else{
                return
            }
            
            if strongSelf.playerView.alpha < 0.5{
                return
            }
            
            strongSelf.barrage_container_view.data_array = array
            
            strongSelf.barrage_container_view.play()
            
            strongSelf.barrage_container_view.alpha = 1
            
            strongSelf.child_model?.commentCount = num
            
            strongSelf.refresh_other_data()
        }
        
        /*
        if let id = child_model?.group_id.string,let array = ST_BTVideoBarrageAdapter.shared.findBarrages(groupId: id){
        }*/
        
    }
    
    
    func insert_barrage(content:String){
        
        guard let avatar = ST_BTUserInfoManager.shared.current_account_info?.userinfo?.avatar else { return  }
        
        let bm = ST_BarrageModel()
        
        bm.reply_content = content
        //    16进制 ex: FFFFFF
        bm.reply_color = "000000"
        
        if ST_BTUserInfoManager.shared.additional_attributes?.anonymousRemark == true{
            
            bm.is_vip = false
            
            bm.avatar = "http://static.duluduludala.com/man-6-5598825401599445941"
            
        }else{
            
            bm.is_vip = FETCH_MEMBER_STATUS() == .subscribe
            
            bm.avatar = avatar
        }
        
        
        
        self.barrage_container_view.insert(barrage: bm)
        
        
        self.child_model?.commentCount += 1
        
        let n = self.child_model?.commentCount ?? 0
        
        let commentNumber = NSMutableAttributedString.init(string: n.st_number_description())
        
        commentNumber.addAttributes(comment_btn_attr, range: NSRange.init(location: 0, length: commentNumber.length))
        
        comment_btn.setTitleForAllStates(commentNumber)
        
        
    }
    
    @objc fileprivate func push_pec_list_handle(){
        
        guard let model = child_model else { return }
        
        var displayPerson = false
        
        if  model.peculiarityType == ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex?.rawValue{
            displayPerson = true
        }
        
        
        if  displayPerson{
            
             let  vc =  ST_PeculiarityDetailShowPersonController.init(peculiarity_id: model.feature_id)
           
            GlobalPresent(toController: vc)
            
        }else{
            
            let  vc =  ST_PeculiarityDetailShowTraitController.init(peculiarity_id: model.feature_id)
            
            GlobalPresent(toController: vc)
        }
        
    }
    
    @objc fileprivate func push_group_handle(){
        
        guard let item = child_model else { return  }
        
        let vc = ST_PeculiarityGroupViewController.init(accid: item.accid, groupId: item.group_id.string, peculiarity_id: item.feature_id.string, firstPhotoSize: CGSize.init(width: item.width, height: item.height), remark: item.sign)
        
        let nav = PairsCenterInteractiveNavigationController.init(rootViewController: vc)
        
        nav.overCurrentContext = true
        
        GlobalPresent(toController: nav, animated: true)
        
    }
}





//MARK: - Tag Button
fileprivate class ST_BTTagButton:UIControl {
    
    static let height = 21.cgFloat
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = UIColor.init(white: 0, alpha: 0.3)
        
//        self.cornerRadius = ST_BTTagButton.height/2.0
        
        self.cornerRadius = 6
        
        self.addSubview(cover_image_view)
        cover_image_view.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(5)
            make.width.height.equalTo(15)
        }
        
        self.addSubview(content_label)
        content_label.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-5)
            make.left.equalTo(cover_image_view.snp.right).offset(3)
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func bind(text:String){
        content_label.text = text
    }
    
    fileprivate lazy var cover_image_view:UIImageView = {
         let control = UIImageView()
        control.image = ST_ImageUtils.imageName("TagButton_img")
          return control
      }()
    
    fileprivate lazy var content_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = Color.white
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.semibold)
        return control
    }()
    
}
